package com.shuigu.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shuigu.constants.HttpStatus;
import com.shuigu.exception.ServiceException;
import com.shuigu.pojo.dto.*;
import com.shuigu.service.ISysUserService;
import com.shuigu.service.IUmsMenuService;
import com.shuigu.service.IUmsRoleService;
import com.shuigu.pojo.entity.UmsMenu;
import com.shuigu.pojo.entity.UmsRole;
import com.shuigu.pojo.entity.UmsSysUser;
import com.shuigu.pojo.vo.RoleMenuVO;
import com.shuigu.pojo.vo.UserInfoVO;
import com.shuigu.pojo.vo.UserRoleVO;
import com.shuigu.mapper.UmsSysUserMapper;
import com.shuigu.response.PageResult;
import com.shuigu.utils.OffMp;
import com.shuigu.utils.ToMp;
import com.shuigu.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 *
 */
@Service
@Slf4j
public class SysUserServiceImpl implements ISysUserService {

    private final UmsSysUserMapper sysUserMapper;
    private final IUmsRoleService sysRoleService;
    private final IUmsMenuService sysMenuService;
    private final PasswordEncoder passwordEncoder;

    public SysUserServiceImpl(UmsSysUserMapper sysUserMapper,IUmsMenuService sysMenuService,
                              IUmsRoleService sysRoleService,PasswordEncoder passwordEncoder) {
        this.sysUserMapper = sysUserMapper;
        this.sysMenuService = sysMenuService;
        this.sysRoleService = sysRoleService;
        this.passwordEncoder = passwordEncoder;
    }


    @Override
    public UserInfoVO searchUserInfo() {
        // 获取用户id
        Long userId = SecurityUtils.getUserId();
        UmsSysUser umsSysUser = sysUserMapper.selectById(userId);
        if(ObjectUtil.isNull(umsSysUser)) {
            throw new ServiceException(HttpStatus.FORBIDDEN,"");
        }

        UserInfoVO userInfoVO = new UserInfoVO();
        BeanUtil.copyProperties(umsSysUser,userInfoVO);
        return userInfoVO;
    }

    @Override
    public PageResult<UserRoleVO> getUserRoleList(UserRoleParamDto userRoleParamDto) {
        Page<UserRoleVO> mpPage = new ToMp().toMpPage(userRoleParamDto);
        // 解决sql count异常，关闭优化后的 Count SQL
        mpPage.setOptimizeCountSql(false);
        List<UserRoleVO> userRoleVO = sysUserMapper.selectUserRole(mpPage,userRoleParamDto);
        log.info("现在的时间{},{}",System.currentTimeMillis(), LocalDateTime.now());
        mpPage.setRecords(userRoleVO);
        return OffMp.of(mpPage);
    }

    @Override
    public Boolean deleteUserRole(Long[] ids) {
        List<Long> list = Arrays.asList(ids);
        boolean flag = sysUserMapper.deleteUserRoleByIds(list);
        return flag;
    }

    @Override
    public int insertUserRole(UserRoleDto userRoleDto) {
        return sysUserMapper.saveUserRoel(userRoleDto);
    }

    @Override
    public List<UmsRole> findAllRoel() {
        List<UmsRole> roleList = sysRoleService.list();
        return roleList;
    }

    @Override
    public PageResult<RoleMenuVO> getRoleMenuList(RoleMenuParamDto roleMenuParamDto) {
        Page<RoleMenuVO> mpPage = new ToMp().toMpPage(roleMenuParamDto);
        // 解决sql count异常，关闭优化后的 Count SQL
        mpPage.setOptimizeCountSql(false);
        List<RoleMenuVO> roleMenuVO = sysUserMapper.selectRoleMenu(mpPage,roleMenuParamDto);
        mpPage.setRecords(roleMenuVO);
        return OffMp.of(mpPage);
    }

    @Override
    public Boolean deleteRoleMenu(Long[] ids) {
        List<Long> list = Arrays.asList(ids);
        boolean flag = sysUserMapper.deleteRoleMenuByIds(list);
        return flag;
    }

    @Override
    public int insertRoleMenu(RoleMenuDto roleMenuDto) {
        return sysUserMapper.saveRoleMenu(roleMenuDto);
    }

    @Override
    public List<UmsMenu> findAllMenu() {
        List<UmsMenu> menuList = sysMenuService.list();
        return menuList;
    }

    // 用户注册
    @Transactional
    @Override
    public String registerUser(UserRegisterDto userRegisterDto) {
        if(userRegisterDto.getMobile() ==null || userRegisterDto.getMobile().trim().equals("")){
            throw new ServiceException(HttpStatus.BAD_REQUEST,"手机格式有误");
        }
        UmsSysUser umsSysUser = sysUserMapper.selectOne(new LambdaQueryWrapper<UmsSysUser>().eq(UmsSysUser::getMobile, userRegisterDto.getMobile()));
        if(umsSysUser != null){
            throw new ServiceException(HttpStatus.ERROR,"手机号已被注册");
        }

        userRegisterDto.setPassword(passwordEncoder.encode(userRegisterDto.getPassword()));

        String username = "user_" + UUID.randomUUID().toString().replace("-","").substring(0,10);
        userRegisterDto.setUsername(username);
        userRegisterDto.setCreateUser(username);
        userRegisterDto.setUpdateUser(username);

        UmsSysUser user = BeanUtil.copyProperties(userRegisterDto, UmsSysUser.class);
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());

        sysUserMapper.insert(user);
        // 为注册用户初始化普通用户角色
        UserRoleDto userRoleDto = UserRoleDto.builder()
                .userId(user.getId())
                .roleId(Long.valueOf(Integer.valueOf(3).toString()))
                .build();
        insertUserRole(userRoleDto);

        return username;
    }

}
